package com.tbit.uqbike.client.handler.borrowbikehandler;

import com.tbit.common.utils.TraceUtil;
import com.tbit.uqbike.client.common.ResultMsg;
import com.tbit.uqbike.client.constant.DepositStateConstant;
import com.tbit.uqbike.client.dao.core.BorrowCheckConfigLogDao;
import com.tbit.uqbike.client.dao.core.LeaderAccountDao;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.borrowbike.BorrowCheckConfigLog;
import com.tbit.uqbike.client.pojo.newEntity.LeaderAccount;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.vo.borrow.BorrowBikeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author lh2
 * @ClassName: DepositCheckHandler
 * @Description: 押金校验处理器
 * @date 2023-07-26 06:01:09
 */
@Slf4j
@Component
public class DepositCheckHandler extends AbstractCheckHandler {
    @Autowired
    private UserService userService;
    @Autowired
    private AccountConfigService accountConfigService;
    @Autowired
    private LeaderAccountDao leaderAccountDao;
    @Autowired
    private AdAccountDepositService adAccountDepositService;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private AgentDepositVipService agentDepositVipService;
    @Autowired
    private BorrowCheckConfigLogDao borrowCheckConfigLogMapper;

    @Override
    public ResultMsg handle(BorrowBikeVO vo, String serialNO) {
        log.info("【押金校验处理器】校验开始...");
        // 降级：如果配置了降级，则跳过此处理器，执行下一个处理器
        if (super.getConfig().getDown() == 1) {
            log.info("【押金校验处理器】被降级，已自动跳过！");
            return super.next(vo, serialNO);
        }

        User user = vo.getUser();
        Machine machine = vo.getMachine();
        AccountConfig accountConfig = accountConfigService.getByAccountId(machine.getAccountId());
        /** 未开启微信支付分,并且用户押金状态是支付分免押 */
        if (accountConfig != null && accountConfig.getWxZffMm() == 0
                && user.getDepositState() == DepositStateConstant.DEPOSIT_STATE_SCORE) {
            /** 用户提交押金金额大于0 */
            if (user.getDepositMoney() > 0) {
                userService.updateDeposit(user.getUserId(), DepositStateConstant.DEPOSIT_STATE_PAY);
                user.setDepositState(DepositStateConstant.DEPOSIT_STATE_PAY);
            } else {
                userService.updateDeposit(user.getUserId(), DepositStateConstant.DEPOSIT_STATE_NOTPAY);
                user.setDepositState(DepositStateConstant.DEPOSIT_STATE_NOTPAY);
            }
        }

        Integer rideNum = 0;
        List<RideLog> rideLogs = rideLogService.getByUserId(user.getUserId());
        if (rideLogs.size() > 0) {
            rideNum = rideLogs.size();
        }
        /** 兼容领导账号不需要购买 */
        LeaderAccount leaderAccount = leaderAccountDao.getByPhone(user.getPhone(), user.getAccountId());
        if (leaderAccount == null || System.currentTimeMillis() >= leaderAccount.getExpireTime().getTime()) {
            AdAccountDeposit adAccountDeposit = adAccountDepositService.getByAccountId(machine.getAccountId());
            AgentDepositVip agentDepositVip = agentDepositVipService.getByUserId(user.getUserId(),
                    machine.getAccountId());
            /** 判断代理商是否要求购买免押套餐 */
            if (adAccountDeposit != null && adAccountDeposit.getDepositVip() == 1
                    && (user.getDepositState() != DepositStateConstant.DEPOSIT_STATE_PAY
                    && user.getDepositState() != DepositStateConstant.DEPOSIT_STATE_VIRTUAL
                    && user.getDepositState() != DepositStateConstant.DEPOSIT_STATE_SCORE)
                    && rideNum >= adAccountDeposit.getFreeTimes()) {
                if (agentDepositVip == null) {
                    return ResultMsg.fail(-3048, "请先购买免押套餐", TraceUtil.getTraceIdByLocal());
                }
                if (agentDepositVip != null && !DateTimeUtil.isDepositValid(agentDepositVip.getExpireDt())) {
                    return ResultMsg.fail(-3048, "请先购买免押套餐",TraceUtil.getTraceIdByLocal());
                }
            }
            /** 判断是否免押会员,免押会员期间不需要提交押金 */
            if ((agentDepositVip == null || !DateTimeUtil.isDepositValid(agentDepositVip.getExpireDt()))
                    && adAccountDeposit != null && rideNum >= adAccountDeposit.getFreeTimes()) {
                /** 判断是是否学生认证，学生认证了，不需要提交押金 */
                /** 兼容虚拟押金功能，押金状态为虚拟押金也不用提交押金 */
                if (user.getDepositState() != DepositStateConstant.DEPOSIT_STATE_STUDENT
                        && user.getDepositState() != DepositStateConstant.DEPOSIT_STATE_VIRTUAL
                        && user.getDepositState() != DepositStateConstant.DEPOSIT_STATE_SCORE) {
                    /** 查询用户是否提交押金 */
                    if (user.getDepositState() == DepositStateConstant.DEPOSIT_STATE_RETURNING) {
                        return ResultMsg.fail(-3003, "押金退还中,不能借车",TraceUtil.getTraceIdByLocal());
                    }
                    if (user.getDepositState() == DepositStateConstant.DEPOSIT_STATE_FROZEN) {
                        return ResultMsg.fail(-3033, "押金冻结，不能借车",TraceUtil.getTraceIdByLocal());
                    }
                    /** 未提交押金 */
                    if (user.getDepositState() == 0 && adAccountDeposit.getDeposit() > 0) {
                        return ResultMsg.fail(-3002, "请先提交押金",TraceUtil.getTraceIdByLocal());
                    }
                    /** 需要补交押金 */
                    if ((user.getDepositState() == DepositStateConstant.DEPOSIT_STATE_PAY)
                            && (adAccountDeposit.getDeposit() > user.getDepositMoney())) {
                        return ResultMsg.fail(-3014, "提交的押金不足借此车，请补足押金再借",TraceUtil.getTraceIdByLocal());
                    }
                }
            }
        }

        log.info("【押金校验处理器】校验通过！");
        BorrowCheckConfigLog bccLog = borrowCheckConfigLogMapper.findByNameAndSerialNO(
                this.getConfig().getHandlerName(), serialNO);
        if (bccLog != null) {
            bccLog.setExecuteResult(1);
            borrowCheckConfigLogMapper.updateByPrimaryKeySelective(bccLog);
        }
        // 执行下一个处理器
        return super.next(vo, serialNO);
    }

}
